import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Tooltip,
  Rate,
  Checkbox,
  Tag,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Ellipsis from '@/components/Ellipsis';
import IconButton from '@/components/IconButton';
import MyIcon from '@/components/MyIcon';
import TooltipIcon from '@/components/TooltipIcon';
import get from 'lodash/get';

import styles from './Manage.less';
import Link from 'umi/link';
import { stringify } from 'querystring';
import { SERVICE_STATUS } from '@/Constants';

const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea, Search } = Input;
const { Option } = Select;
const RadioGroup = Radio.Group;

@connect(({ base, product, loading }) => ({
  cargoTypes: base.cargoTypes,
  products: product.products,
  productGroups: product.productGroups,
  loading: loading.effects['product/fetch'],
  deleteLoading: loading.effects['product/delete'],
  submitAuditLoading: loading.effects['product/submitAudit'],
}))
@Form.create()
class Manage extends PureComponent {
  state = {
    formValues: {},
    selectedRows: [],
    brandClass: {
      环球通: 'huanqiutong',
      智舱宝: 'zhicangbao',
      如意鲜: 'ruyixian',
      包达天下: 'baodatianxia',
      如翼达: 'ruyida',
    },
  };

  columns = [
    {
      title: '序号',
      width: 130,
      render: (text, record, index) => {
        return <span>{this.calcIndex(index)}</span>;
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
      render: (text, record) => {
        let query = {
          productId: record.id,
          backRoute: '/product/manage',
          entry: 'manage',
          viewId: 'product',
        };
        let brandClassName = `iconcmn---${this.state.brandClass[record.brandName]}`
        let icon = { '草稿': 'iconoss---caogao', '待审核': 'iconoss---daishenhe-dairenzheng-daichuli', '已审核': 'iconoss---yishenhe-yichuli' }[record.approveStatusName || '草稿']
        return (
          <div className={styles.name}>
            {record.status === SERVICE_STATUS.AUDITTED && !record.isOnline && <TooltipIcon width='-90px' title='停用' icon='iconoss---tingyong'></TooltipIcon>}
            <TooltipIcon width='-60px' title={record.approveStatusName} icon={icon}></TooltipIcon>
            <TooltipIcon title={record.brandName} icon={brandClassName}></TooltipIcon>
            <Link to={`/product/manage/add/base?${stringify(query)}`} style={{ marginRight: 8 }}>
              {text}
            </Link>
          </div>
        );
      },
    },
    {
      title: '编码',
      dataIndex: 'code',
    },
    {
      title: '产品组',
      dataIndex: 'groupName',
    },
    {
      title: '货物类型',
      dataIndex: 'cargoTypeNameList',
      render: text => {
        return <span>{text.toString()}</span>;
      },
    },
    {
      title: '产品介绍',
      dataIndex: 'introduction',
      render: text => {
        return (
          <Ellipsis tooltip length={30}>
            {text}
          </Ellipsis>
        );
      },
    }
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({ type: 'base/fetchCargoTypes' });
    dispatch({ type: 'product/fetchGroups' });
    this.searchProducts();
  }

  calcIndex = index => {
    const { products } = this.props;
    let currentPage = get(products, 'pagination.currentPage') || 1;
    let pageSize = get(products, 'pagination.pageSize') || 50;
    return (currentPage - 1) * pageSize + index + 1;
  };

  resetConditions = () => {
    const { form } = this.props;
    form.resetFields();
    this.searchProducts();
  };

  searchProducts = ({ pageIndex = 1, pageSize = 50, ...rest } = {}) => {
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      let payload = {
        ...fieldsValue,
        pageIndex,
        pageSize,
        ...rest,
      };
      dispatch({
        type: 'product/fetch',
        payload: {
          queryParams: payload,
        },
      });
    });
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      pageIndex: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    this.searchProducts(params);
    this.setState({
      selectedRows: [],
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleDeleteProduct = () => {
    const { dispatch, deleteLoading } = this.props;
    if (deleteLoading) return
    const { selectedRows } = this.state;
    Modal.confirm({
      title: '删除产品',
      content: '确定删除已选产品吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        return dispatch({
          type: 'product/delete',
          payload: {
            data: selectedRows.map(item => item.id),
          },
        }).then(res => {
          if (res.errorCode === 0) {
            message.success('删除成功');
            this.searchProducts();
          }
        });
      },
    });
  };

  handleSubmitAudit = () => {
    const { dispatch, submitAuditLoading } = this.props;
    if (submitAuditLoading) return
    const { selectedRows } = this.state;
    Modal.confirm({
      title: '提交审核',
      content: '确定提交已选产品吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        return dispatch({
          type: 'product/submitAudit',
          payload: {
            data: selectedRows.map(item => item.id),
          },
        }).then(res => {
          if (res.errorCode === 0) {
            message.success('提交成功');
            this.searchProducts();
          }
        });
      },
    });
  };

  canAudit = () => {
    const { selectedRows } = this.state;
    return selectedRows.every(item => item.status === 0);
  };

  render() {
    const {
      form: { getFieldDecorator },
      products,
      cargoTypes,
      productGroups,
      loading,
      deleteLoading,
      submitAuditLoading
    } = this.props;
    const { selectedRows } = this.state;

    let query = {
      backRoute: '/product/manage',
      entry: 'manage',
    };

    return (
      <PageHeaderWrapper title="新建产品">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>
              <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={8} sm={24}>
                  <FormItem label="关&ensp;键&ensp;字">
                    {getFieldDecorator('q')(
                      <Input placeholder="请输入产品名称或编码" maxLength={30} />
                    )}
                  </FormItem>
                </Col>
                <Col md={8} sm={24}>
                  <FormItem label="货物类型">
                    {getFieldDecorator('cargoType')(
                      <Select
                        allowClear
                        showSearch
                        optionFilterProp="children"
                        style={{ width: '100%' }}
                      >
                        {cargoTypes.map(val => (
                          <Option key={val.code} value={val.code}>{`${val.name}`}</Option>
                        ))}
                      </Select>
                    )}
                  </FormItem>
                </Col>
                <Col md={8} sm={24}>
                  <FormItem label="产&ensp;品&ensp;组">
                    {getFieldDecorator('group')(
                      <Select
                        allowClear
                        showSearch
                        optionFilterProp="children"
                        style={{ width: '100%' }}
                      >
                        {productGroups.map(val => (
                          <Option key={val.id} value={val.id}>{`${val.name}`}</Option>
                        ))}
                      </Select>
                    )}
                  </FormItem>
                </Col>
              </Row>
              <Row type="flex" justify="space-between" gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={8} sm={24}>
                  <FormItem label="状&emsp;&emsp;态" style={{ flex: 1 }}>
                    {getFieldDecorator('status', {
                      initialValue: 0,
                    })(
                      <Select
                        allowClear
                        onChange={() => setTimeout(this.searchServices, 0)}
                        optionFilterProp="children"
                        style={{ width: '100%' }}
                      >
                        <Option value={0}>草稿</Option>
                        <Option value={1}>待审核</Option>
                        <Option value={2}>已审核</Option>
                      </Select>
                    )}
                  </FormItem>
                </Col>
                <Col>
                  <Button style={{ float: 'right' }} onClick={this.resetConditions}>
                    重置
                  </Button>
                  <Button style={{ float: 'right', marginRight: 24 }} type="primary" onClick={() => this.searchProducts()}>
                    查询
                  </Button>
                </Col>
              </Row>
            </div>
            <div className={styles.tableListOperator}>
              <Link to={`/product/manage/add/base?${stringify(query)}`} style={{ color: '#666' }}>
                <IconButton icon="icon-add" title="添加" />
              </Link>
              {selectedRows.length > 0 &&
                this.canAudit() && (
                  <IconButton
                    icon="icon-delete"
                    loading={deleteLoading}
                    title="删除"
                    style={{ marginLeft: 10 }}
                    onClick={() => this.handleDeleteProduct()}
                  />
                )}
              {selectedRows.length > 0 &&
                this.canAudit() && (
                  <IconButton
                    icon="iconcmn---tijiao"
                    loading={submitAuditLoading}
                    title="提交审核"
                    style={{ marginLeft: 10 }}
                    onClick={this.handleSubmitAudit}
                  />
                )}
            </div>
            <StandardTable
              rowKey="id"
              showCheckbox
              selectedRows={selectedRows}
              loading={loading}
              data={products}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default Manage;
